#-------------------------------------------------------------------------------
# Name:        pdf_to_png_converter.py
# Purpose:     Classes to convert PDF file to PNG images
#
# Authors:     John Graves <john.graves@slidespeech.com>
#
# Copyright:   (c) Slidespeech Ltd 2012
# Licence:     MIT license
#-------------------------------------------------------------------------------

import os, sys, shutil

# Conversion is the same for all platforms,
# except the ImageMagick utility
#  convert.exe
# conflicts with the Windows utility
#  convert.exe
# which converts FAT volumes to NTFS.
if sys.platform.startswith("linux"):
    from pdf_converter_linux import *
elif sys.platform.startswith("darwin"):
    from pdf_converter_osx import *
elif sys.platform.startswith("win"):
    from pdf_converter_windows import *
else:
    raise NotImplementedError()

from utility import *

from converter import Converter

class PdfToPngConverter(Converter):
    def __init__(self, pdfPath, pdfFile='contents.pdf', pngPath=None, previous=None):
        Converter.__init__(self, previous)
        self._pdfPath = pdfPath
        self._pdfFile = pdfFile
        if pngPath is None:
            if hasattr(self,'_pngPath'):
                pass
            else:
                self._pngPath = self.tempDir()
        else:
            self._pngPath = pngPath
        self._tempDir = self._pngPath
        for dependency in PDFConfig.dependencies:
            if findDependency(dependency) is None:
                raise RuntimeError("Missing dependency: {0}".format(dependency))

    def _convertImpl(self):
        """Extracts PNG image files from the given PDF file.
        Returns a list with the image file names (slide-0.png, slide-1.png, ...)
        as separate items."""

        self._imageDir = os.path.join(self._pngPath, "images", "CONTENTS")
        try:
            os.makedirs(self._imageDir)
        except OSError:
            # dir already exists, shouldn't happen
            pass

        try:
            pdfToPng(self._pdfPath, self._imageDir, pdfFile=self._pdfFile)

        except Exception as ex:
            # FIXME: record exception details
            raise RuntimeError("Could not generate images" + \
        " from PDF file {0} on path {1}".format(self._pdfFile,self._pdfPath) + \
        "\nCheck that conversion utility is on path.")

        imageList = []
        for filename in os.listdir(self._imageDir):
            (base, suffix) = os.path.splitext(filename)
            if suffix == '.png':
                imageList.append(filename)

        if 'slide.png' in imageList:
            # This happens with single page PDF files
            # The file needs to be renamed slide-0.png
            shutil.copyfile(os.path.join(self._imageDir, 'slide.png'),
                            os.path.join(self._imageDir, 'slide-0.png'))
            os.remove(os.path.join(self._imageDir, 'slide.png'))
            imageList.remove('slide.png')
            imageList.insert(0,'slide-0.png')

        # add the image file locations to the script
        try:
            seq = self.script()['S']

            # if sequence has notes
            if len(seq)>0:
                # check that we have the same number of images as notes
                if len(imageList) != len(seq):
                    ex = ConverterError(_("Number of images and notes is different"))
                    raise ex
                else:
                    # add images
                    for index, q in enumerate(seq):
                        q['i'] = imageList[index]
            else:
                for index in range(len(imageList)):
                    q = {}
                    q['i'] = imageList[index]
                    seq.append(q)

        except KeyError as e:
            ex = ConverterError(_("Field missing in slide script"), e)
            raise ex

if __name__ == "__main__":
    # a simple test/demo
    c = PdfToPngConverter(pdfPath='test',pdfFile='test3.pdf')
    c.convert()
    print(c.script())
